/**
 * 
 */
package com.yunyike.controller.quotation;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.ExcelConstants;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.dto.QuotationMerchandiseDTO;
import com.yunyike.model.Quotation;
import com.yunyike.service.QuotationService;
import com.yunyike.utils.QuotationMerchandiseExcelUtil;


@Controller
@RequestMapping(value=RequestConstant.QUOTATIONMERCHANDISE)
public class QuotationMerchandiseController extends BaseController{

	private Logger log = LoggerFactory.getLogger(QuotationMerchandiseController.class);
	
	@Autowired
	private QuotationService quotationService;
	
	
	@RequestMapping(value=RequestConstant.QUOTATIONMERCHANDISELIST+"/{quotationId}/{skuStatu}")
	public String toScreenList(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId,
			@PathVariable(value="skuStatu") String skuStatu) {
		log.info("QUOTATIONMERCHANDISE getList --进入excel商品列表页--quotationId="+quotationId+",skuStatu="+skuStatu);
		if(StringUtils.isBlank(quotationId)){
			log.info("出错：：：请求参数有误quotationId为空，稍后重试");
			request.setAttribute("message", "请求参数有误，稍后重试");
			return ResponseConstant.QUOTATIONLIST;
		}
		request.setAttribute("quotationId", quotationId);
		request.setAttribute("skuStatu", skuStatu);
		request.setAttribute("skuStatusMap", CommonConstant.getSkuStatusMap());
		request.setAttribute("statusMap", CommonConstant.getStatusMap());
		if("-1".equals(skuStatu))skuStatu="";
		List<QuotationMerchandiseDTO> list = new ArrayList<QuotationMerchandiseDTO>();
		try {
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			if (quotation != null) {
				request.setAttribute("quotationName", quotation.getQuotationName());
				if (!"".equals(quotation.getQuotationLink())) {
					String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
					String middleexcel = ExcelConstants.EXCEL_MIDDLEPATH + excelName;
					File file = new File(middleexcel);
					if(file.exists()){
						log.info("中间excel表已存在，获取excel数据---");
						String emfStr = QuotationMerchandiseExcelUtil
								.readMiddleExcel(middleexcel, list, skuStatu, "");
						request.setAttribute("picturePath", emfStr);
						request.setAttribute("quotMerchlist", list);
						return ResponseConstant.QUOTATIONLIST;
					}
					log.info("中间excel表不存在--从原excel表读取数据--");
					String message = QuotationMerchandiseExcelUtil
							.readExcelToMerchList(ExcelConstants.EXCEL_SAVEPATH, excelName, list);
					if (!"".equals(message)) {
						request.setAttribute("message", message);
						log.info("出错：：："+message);
						return ResponseConstant.QUOTATIONLIST;
					}
					log.info("生成中间excel表--");
					String emfStr = QuotationMerchandiseExcelUtil
						.writeMiddleExcel(list,excelName,ExcelConstants.EXCEL_SAVEPATH);
					request.setAttribute("picturePath", emfStr);
					request.setAttribute("quotMerchlist", list);
				}
			} else {
				request.setAttribute("message", "请求参数有误，稍后重试");
				log.info("出错：：：请求参数有误quotationId在数据库搜索不到数据，稍后重试");
				return ResponseConstant.QUOTATIONLIST;
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "发生异常");
		}
		return ResponseConstant.QUOTATIONLIST;
	}
	
	@ResponseBody
	@RequestMapping(value=RequestConstant.QUOTATIONADDMERCHANDISE+"/{quotationId}")
	public String save(String data,HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId) throws IOException{
		
		log.info("QUOTATIONMERCHANDISE save ---quotationId="+quotationId);
		if(StringUtils.isBlank(data)){
			log.info("请求参数有误，稍后重试");
//			request.setAttribute("message", "请求参数有误，稍后重试");
			return "请求参数有误，稍后重试";
		}
		try {
			boolean checkSaved = true;
			Map<Integer,String> canbeNull = new HashMap<Integer,String>(); 
			canbeNull.put(0, "Status");
			canbeNull.put(1, "SkuStatus");
			canbeNull.put(8, "JingdongPrice");
			canbeNull.put(13, "ReferenceInternetUrl");
			canbeNull.put(16, "MerchandiseCollection");
			canbeNull.put(17, "MerchandiseSpecDesc");
			canbeNull.put(18, "MerchandiseDesc");
			canbeNull.put(19, "Remark");
			canbeNull.put(20, "cost");
			String[] params = data.split("::");
			for (int i = 0; i < params.length; i++) {
				String param = params[i];
				if("undefined".equals(param)) params[i]="";
				if(StringUtils.isBlank(params[i])&&!canbeNull.containsKey(i)){
					checkSaved=false;
				}
			}
			log.info("保存的行的数据params：："+Arrays.toString(params));
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			QuotationMerchandiseDTO dto = new QuotationMerchandiseDTO();
			dto.setQuotationId(quotationId);
			log.info("将参数复制给dto");
			checkStringToDTO(dto, params);
			if(checkSaved){
				dto.setStatus(CommonConstant.MERCHANDISE_SAVED);
			}else{
				dto.setStatus(CommonConstant.MERCHANDISE_SAVING);
			}
			String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
			log.info("更新中间EXcel表的该行数据--");
			String message = QuotationMerchandiseExcelUtil
				.updateMiddleExcel(dto, excelName, ExcelConstants.EXCEL_MIDDLEPATH);
			if(!"".equals(message)){
				return message;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "发生异常";
		}
		log.info("QUOTATIONMERCHANDISE save ---END=");
		return "success";
	}
	private void checkStringToDTO(QuotationMerchandiseDTO dto,String[] params ){

		dto.setStatus(params[0]==""?CommonConstant.MERCHANDISE_SAVING:Integer.parseInt(params[0]));
		dto.setSkuStatus(params[1]==""?CommonConstant.SKU_UNTREATED:Integer.parseInt(params[1]));
		dto.setRowIndex(Integer.parseInt(params[2]));
		dto.setRate(params[3]==""?0:Double.parseDouble(params[3]));
		dto.setEuropePrice(params[4]==""?0:Double.parseDouble(params[4]));
		dto.setEuropePriceRmb(params[5]==""?0:Double.parseDouble(params[5]));
		dto.setOfficePrice(params[6]==""?0:Double.parseDouble(params[6]));
		dto.setEuropeOfficeDiscount(params[7]==""?0:Double.parseDouble(params[7]));
		dto.setJingdongPrice(params[8]==""?0:Double.parseDouble(params[8]));
		dto.setSkuPrice(params[9]==""?0:Double.parseDouble(params[9]));
		dto.setRatio1(params[10]==""?0:Double.parseDouble(params[10]));
		dto.setDiscountPrice(params[11]==""?0:Double.parseDouble(params[11]));
		dto.setRatio2(params[12]==""?0:Double.parseDouble(params[12]));
		dto.setReferenceInternetUrl(params[13]);
		dto.setMerchandiseName(params[14]);
		dto.setMerchandiseColor(params[15]);
		dto.setMerchandiseCollection(params[16]);
		dto.setMerchandiseSpecDesc(params[17]);
		dto.setMerchandiseDesc(params[18]);
		dto.setRemark(params[19]);
		
	}
	
	@ResponseBody
	@RequestMapping(value=RequestConstant.QUOTATIONMODIFYMERCHANDISE+"/{quotationId}"+"/{rowIndex}")
	public String pushMerchandise(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId,
			@PathVariable(value="rowIndex") String rowIndex,String status,String stockQty) throws IOException{
		
		log.info("QUOTATIONMERCHANDISE push ---quotationId="+quotationId+",rowIndex="+rowIndex
				+",status="+status+",stockQty="+stockQty);
		if(StringUtils.isBlank(quotationId)||StringUtils.isBlank(rowIndex)){
//			request.setAttribute("message", "请求参数有误，稍后重试");
			return "请求参数有误，稍后重试";
		}
		try {
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			QuotationMerchandiseDTO dto = new QuotationMerchandiseDTO();
			dto.setQuotationId(quotationId);
			if("3".equals(status)){
				dto.setStatus(CommonConstant.MERCHANDISE_REVIEW);
			}else{
				dto.setSkuStatus(CommonConstant.SKU_STOCKPILING_REVIEW);
				dto.setSummarySkuQty(Integer.parseInt(stockQty));
			}
			dto.setRowIndex(Integer.parseInt(rowIndex));
			String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
			log.info("商品发布审核：更新中间EXcel表的状态");
			String message = QuotationMerchandiseExcelUtil
				.modifyMerchandiseStatu(dto,excelName, ExcelConstants.EXCEL_MIDDLEPATH);
			if(!"".equals(message)){
				return message;
			}
			if(CommonConstant.NUMBER_3>quotation.getQuotationStatus()){
				quotation.setQuotationStatus(CommonConstant.NUMBER_3);
				quotationService.updateByPrimaryKeySelective(quotation);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "发生异常";
		}
		log.info("QUOTATIONMERCHANDISE push ---END=");
		return "success";
	}
	
	@RequestMapping(value=RequestConstant.QUOTATIONTRATE+"/{quotationId}")
	public String quotationTrate(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId) throws IOException{
		
		log.info("QUOTATIONMERCHANDISE quotationTrate ---quotationId="+quotationId);
		if(StringUtils.isBlank(quotationId)){
			request.setAttribute("message", "请求参数有误，稍后重试");
			return ResponseConstant.REDIRECT+RequestConstant.QUOTATION+RequestConstant.QUOTATION_LIST;
		}
		try {
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			if(CommonConstant.NUMBER_2>quotation.getQuotationStatus()){
				quotation.setQuotationStatus(CommonConstant.NUMBER_2);
				int num = quotationService.updateByPrimaryKeySelective(quotation);
				if(num==0){
					request.setAttribute("message", "失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "发生异常");
		}
		log.info("QUOTATIONMERCHANDISE quotationTrate ---END=");
		return ResponseConstant.REDIRECT+RequestConstant.QUOTATION+RequestConstant.QUOTATION_LIST;
	}
	

	@RequestMapping(value=RequestConstant.DOWNLOADEXCEL+"/{quotationId}")
	public String downloadMiddleExcel(HttpServletRequest request, HttpServletResponse response,
			@PathVariable(value="quotationId") String quotationId) throws IOException{
		
		log.info("QUOTATIONMERCHANDISE quotationTrate ---quotationId="+quotationId);
		if(StringUtils.isBlank(quotationId)){
			request.setAttribute("message", "请求参数有误，稍后重试");
			return ResponseConstant.REDIRECT+RequestConstant.QUOTATION+RequestConstant.QUOTATION_LIST;
		}
		try {
			Quotation quotation = quotationService.selectByPrimaryKey(quotationId);
			String excelName = quotation.getQuotationLink().replace(ExcelConstants.EXCEL_SAVEPATH, "");
			String message = QuotationMerchandiseExcelUtil
					.downloadExcel(response, ExcelConstants.EXCEL_SAVEPATH, excelName);
			if(!"".equals(message)){
				log.info("下载中出现问题："+message);
				request.setAttribute("message", message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "发生异常");
		}
		log.info("QUOTATIONMERCHANDISE quotationTrate ---END=");
		return ResponseConstant.QUOTATIONLIST;
	}
	
}
